<?php
if (!isset($common)) require_once '../common.php';

class usersession
{
	private $iduser;
	private $username;
	private $lang;
	private $coordx;
	private $coordy;
	private $tropas; // array
	
	static public function loadSession($username)
	{
		require 'include/dbconnect.php';
		
		//Leer usuario de la BD
		$resultUser = mysql_query("SELECT * FROM users WHERE username='".$username."'");
		if( !$resultUser)
		{
			die('Error: '. mysql_error());
		}
		$rowUser = mysql_fetch_array($resultUser);
		
		//Leer ciudades del usuario
		$resultCity = mysql_query("SELECT * FROM cities WHERE iduser ='".$rowUser["iduser"]."'");
		if( !$resultCity)
		{
			die('Error: '. mysql_error());
		}
		
		//Almacenar parámetros en la sesión
		$_SESSION["iduser"] = $rowUser["iduser"];
		$_SESSION["username"] = $rowUser["username"];
		$_SESSION["lang"] = $rowUser["lang"];
		
		$_SESSION["numcities"] = mysql_num_rows($resultCity);
		
		$ind = 0;
		while( $rowCity = mysql_fetch_array($resultCity) )
		{		
			$_SESSION["idcity"][$ind] = $rowCity["idcity"];
			$_SESSION["coordx"][$ind] = $rowCity["coordx"];
			$_SESSION["coordy"][$ind] = $rowCity["coordy"];
			
			$_SESSION["tropas"][$ind] = array(
				$rowCity["tropas0"],
				$rowCity["tropas1"],
				$rowCity["tropas2"],
				$rowCity["tropas3"],
				$rowCity["tropas4"]
			);
			
			$ind++;	
		}	
		
		//Además, creo la cookie
		setcookie("iduser", $rowUser["iduser"], time()+3600);
		setcookie("username", $rowUser["username"], time()+3600);
		setcookie("lang", $rowUser["lang"], time()+3600);
		
		//Cerrar la cookie
		require 'include/dbdisconnect.php';
	}
}
?>